Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Types of Inheritance

Hierarchical inheritance

Hierarchical inheritance in Java is a type of inheritance where a single class (superclass) is inherited by multiple classes (subclasses). This means that more than one derived class shares the same base class. Here’s the syntax for hierarchical inheritance in Java:
hierarchical inheritance syntax class SuperClass { // members } class SubClass1 extends SuperClass { // members } class SubClass2 extends SuperClass { // members }
In this syntax, SubClass1 and SubClass2 are classes that extend SuperClass. This means that SubClass1 and SubClass2 inherit all the non-private members (fields and methods) of SuperClass. Here’s an example of hierarchical inheritance in Java:
Basic example of hierarchical inheritance in Java //change filename to HierarchicalInheritanceDemo.java // Superclass class Employee { float salary = 40000; } // Subclass 1 class PermanentEmp extends Employee { double hike = 0.5; } // Subclass 2 class TemporaryEmp extends Employee { double hike = 0.35; } public class HierarchicalInheritanceDemo { public static void main(String args[]) { PermanentEmp p = new PermanentEmp(); TemporaryEmp t = new TemporaryEmp(); // All objects of inherited classes can access the variable of class Employee System.out.println("Permanent Employee salary is: " + p.salary); System.out.println("Hike for Permanent Employee is: " + p.hike); System.out.println("Temporary Employee salary is: " + t.salary); System.out.println("Hike for Temporary Employee is: " + t.hike); } }

Output

Permanent Employee salary is: 40000.0 Hike for Permanent Employee is: 0.5 Temporary Employee salary is: 40000.0 Hike for Temporary Employee is: 0.35
In this example, PermanentEmp and TemporaryEmp are subclasses that extend the Employee superclass. The PermanentEmp and TemporaryEmp classes inherit the salary variable from the Employee class, and they also define their own hike variables. In the main method, objects p and t of types PermanentEmp and TemporaryEmp are created. These objects can access both the salary variable and the hike variable. This is a simple demonstration of how hierarchical inheritance works in Java. It allows for code reusability and reduces code duplication.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ inheritance ★ Hierarchical inheritance

Tutorials